import ldap
from ldap.ldapobject import LDAPObject
import re
#def ldapConnect():
#    l = ldap.open('localhost', 389)
#    try:
#        l.simple_bind_s("cn=admin,dc=localnet,dc=org", "nordercode")
#        return l
#    except:
#        return False



class ldapConnect(LDAPObject, object):
    def __init__(self, *args, **kwargs):
        super(ldapConnect, self).__init__("ldap://localhost:389")
        self.simple_bind_s("cn=admin,dc=localnet,dc=org", "nordercode")
        self.set_option(ldap.OPT_REFERRALS, 0)
        
    def modify_s(self, *args, **kwargs):
        res = None
        try:
            res = super(ldapConnect, self).modify_s(*args, **kwargs)
        except Exception, e:
            import sys
            sys.stderr.write("args: %s  message: %s"%(e.args, e.message))
            if e.message["desc"] == "Referral":
                uri = re.search("(ldap://\d+\.\d+\.\d+\.\d+/)", e.message["info"]).group(1)
                l = ldap.initialize(uri) 
                l.simple_bind_s("cn=admin,dc=localnet,dc=org", "nordercode")
                res = l.modify_s(*args, **kwargs)
                l.unbind_s()
        return res 
        
    def add_s(self, *args, **kwargs):
        res = None
        try:
            res = super(ldapConnect, self).add_s(*args, **kwargs)
        except Exception, e:
            import sys
            sys.stderr.write("args: %s  message: %s"%(e.args, e.message))
            if e.message["desc"] == "Referral":
                uri = re.search("(ldap://\d+\.\d+\.\d+\.\d+/)", e.message["info"]).group(1)
                l = ldap.initialize(uri)
                l.simple_bind_s("cn=admin,dc=localnet,dc=org", "nordercode")
                res = l.add_s(*args, **kwargs)
                l.unbind_s()
        return res

    def delete_s(self, *args, **kwargs):
        res = None
        try:
            res = super(ldapConnect, self).modify_s(*args, **kwargs)
        except Exception, e:
            import sys
            sys.stderr.write("args: %s  message: %s"%(e.args, e.message))
            if e.message["desc"] == "Referral":
                uri = re.search("(ldap://\d+\.\d+\.\d+\.\d+/)", e.message["info"]).group(1)
                l = ldap.initialize(uri)
                l.simple_bind_s("cn=admin,dc=localnet,dc=org", "nordercode")
                res = l.delete_s(*args, **kwargs)
                l.unbind_s()
        return res
            